package com.heima.media.service.impl;

;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser wmUser) {
        // 判断用户是否存在,根据 ap_user_id 进行判断
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getApUserId,wmUser.getApUserId());
        int count = this.count(queryWrapper);
        if(count==0){
            wmUser.setCreatedTime(new Date());
            this.save(wmUser);
        }
        return ResponseResult.okResult(wmUser);
    }

    @Override
    public ResponseResult login(LoginDto dto) {
        //        1、判断是否缺少参数
        if(dto==null || (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

//        2、根据用户名查询用户
//        select * from wm_user where name=??
        LambdaQueryWrapper<WmUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmUser::getName,dto.getName());
        WmUser one = this.getOne(queryWrapper);

        if(one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AD_USER_NOT_EXIST);
        }

//        3、再比较密码
//        把明文+salt再md5加密  加密后再和表中的password比较
//        dto.getPassword()是明文的
        String password_mi = DigestUtils.md5Hex(dto.getPassword() + one.getSalt());
        if (!StringUtils.equals(one.getPassword(),password_mi)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }

//        4、返回前端需要的数据
//        {
//            "user":{},
//            "token":""
//        }
        Map resultMap = new HashMap();
//        去除one对象中的敏感数据
        one.setPassword("");
        one.setPhone("");
        one.setEmail("");
        one.setSalt("");
        resultMap.put("user",one);

        Map<String, Object> claimMaps = new HashMap<>();
        claimMaps.put("userId",one.getId());
        claimMaps.put("name",one.getName());
        String token = AppJwtUtil.getToken(claimMaps);

        resultMap.put("token",token);


        return ResponseResult.okResult(resultMap);
    }
}

